package com.sinog.auth.config.xss;

import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @desc xss包装
 * @author lzq
 * @date 2021-07-26 12:28
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    /**
     * 对header处理
     * @param name name
     * @return String
     */
    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        return XssUtil.cleanXss(value);
    }

    /**
     * 对参数处理
     * @param name name
     * @return String
     */
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        return XssUtil.cleanXss(value);
    }

    /**
     * 对数值进行处理
     * @param name name
     * @return String[]
     */
    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if(null != values) {
            int length = values.length;
            String[] escapseValues = new String[length];
            for(int i = 0; i < length; i++) {
                escapseValues[i] = XssUtil.cleanXss(values[i]);
            }
            return escapseValues;
        }
        return super.getParameterValues(name);
    }

    /**
     * 主要是针对HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE 获取pathvalue的时候把原来的pathvalue经过xss过滤掉
     * @param name name
     * @return Object
     */
    @Override
    public Object getAttribute(String name) {
        // 获取pathvalue的值
        if(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE.equals(name)) {
            Map<String,Object> uriTemplateVars = (Map<String,Object>)super.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            if(Objects.isNull(uriTemplateVars)) {
                return null;
            }
            Map<String,Object> newMap = new LinkedHashMap<>(16);
            uriTemplateVars.forEach((key,value) -> {
                if(value instanceof String) {
                    newMap.put(key,XssUtil.cleanXss((String)value));
                } else {
                    newMap.put(key,value);
                }
            });
            return newMap;
        } else {
            return super.getAttribute(name);
        }
    }
}